package com.zhxy.handler;

import com.zhxy.bean.User;
import com.zhxy.constants.Constants;
import com.zhxy.result.R;
import com.zhxy.service.RedisService;
import com.zhxy.utils.JSONUtils;
import com.zhxy.utils.JWTUtils;
import com.zhxy.utils.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        // 用于获取当前认证用户的主体信息
        User user =(User) authentication.getPrincipal();

        // 把User对象转成Json作为负载数据放入JWT
        String userJson = JSONUtils.toJSON(user);

        // 生成JWT
        String jwt = JWTUtils.createJWT(userJson);

        // 将用户登录信息存入Redis中
        redisService.setValue(Constants.REDIS_JWT_KEY+user.getId(),jwt);

        // 设置过期时间
        String rememberMe = request.getParameter("rememberMe");
        if (Boolean.parseBoolean(rememberMe)){
            redisService.expire(Constants.REDIS_JWT_KEY+user.getId(),Constants.TIMEOUT, TimeUnit.SECONDS);
        }else {
            redisService.expire(Constants.REDIS_JWT_KEY+user.getId(),Constants.DEFAULT_TIMEOUT,TimeUnit.SECONDS);
        }

        // 对返回结果进行封装
        R result = R.OK(jwt);

        // 将结果转换成JSON格式
        String json = JSONUtils.toJSON(result);

        // 将结果响应给前端
        ResponseUtils.write(response,json);
    }
}
